<template>
  <view class="container">
    <view class="page-banner">
      <view class="title" v-if="isViewTrainRecord">
        <view class="left">
          <text>答题进度</text>
          <text class="num"
            ><text class="big">{{ doneNum }}</text
            >/{{ paperTotal }}</text
          >
        </view>
      </view>
      <u-line-progress
        class="progress"
        v-if="percent && isViewTrainRecord"
        :percentage="percent"
        :showText="false"
        active-color="#ffffff"
        inactive-color="#a0c3d0"
        height="8"
      ></u-line-progress>
      <view class="grid-body">
        <view class="type">{{ currentExam.typeLabel }}</view>
        <view class="content">{{ currentExam.content }}</view>

        <view
          v-for="(item, index) in currentExam.optionList"
          :key="index"
          class="option"
          :class="{ active: isSelect(item) }"
          @click="handleSelect(item)"
        >
          <text v-if="currentExam.type === '3'">{{ item.content }}</text>
          <text v-else>{{ item.options }}.{{ item.content }}</text>
          <image v-show="isSelect(item)" src="/static/images/online-examination/select.png"></image>
        </view>

        <view class="btn-group">
          <view class="confirm-btn" v-if="currentExam.type === '2'">
            <view class="small-btn small-preview" :class="{ disable: currentPaperIndex == 0 }" @click="handlePreview"
              >上一题</view
            >
            <view class="small-btn small-next" @click="handleNext">{{ isLastTopic ? '提交' : '下一题' }}</view>
            <view class="small-btn small-next" @click="multiTitleConfirm">确定</view>
          </view>
          <view class="pre-nex" v-else>
            <view class="big-btn preview" :class="{ disable: currentPaperIndex == 0 }" @click="handlePreview" style=""
              >上一题</view
            >
            <view class="big-btn next" @click="handleNext" :class="{ disable: !isViewTrainRecord && isLastTopic }"
              >{{ isLastTopic ? '提交' : '下一题' }}
            </view>
          </view>
        </view>

        <view class="analysis-box" v-if="showAnalysis">
          <view class="answer">
            <text>答案：{{ correctAnswer }}</text>
            <text>你的选择：{{ yourAnswer }}</text>
          </view>
          <view class="analysis">
            <text class="big">试题解析：</text>
            <view>{{ questionAnalysis }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="page-footer flex-space-between">
      <view v-if="isViewTrainRecord" class="answer-sheet" @click="handlePopup">
        <image src="/static/images/online-examination/answer-sheet.png"></image>
        答题卡
      </view>

      <view class="btn-group" v-if="isViewTrainRecord">
        <!-- <view class="big-btn pause" @click="saveExamProgress">退出</view> -->
        <view class="big-btn submit" @click="tipDialogVisible = true">提交</view>
      </view>
    </view>

    <tip-dialog v-model="tipDialogVisible" @confirm="handleSubmit" :type="noDoneNum ? '' : 'primary'" :examType="'1'">
      <view>{{ noDoneNum ? '温馨提示' : '恭喜您' }}</view>
      <view>{{ noDoneNum ? `您还有${noDoneNum}题未做，确认提交吗` : `题目已全部答完，确认提交吗` }}</view>
    </tip-dialog>
  </view>
</template>

<script>
import { getExamListByType } from '@/api/educational-training/trainingTasks'
import { get, includes } from 'lodash'
import { mapMutations, mapState, mapActions } from 'vuex'
import TipDialog from './components/TipDialog'
import NavBar from '@/pages/messages/components/nav-bar.vue'

export default {
  name: 'take-part-examination',

  data() {
    return {
      paperList: [],
      correctAnswer: '',
      yourAnswer: '',
      questionAnalysis: '',
      showAnalysis: false,
      isViewTrainRecord: true, //当前是否为查看训练结果
      tipDialogVisible: false,
      typeId: '' // 试题类型ID
    }
  },

  components: {
    TipDialog,
    NavBar
  },

  computed: {
    ...mapState({
      examDetailList: (state) => state.onlineExam.examDetailList,
      currentPaperIndex: (state) => state.onlineExam.currentPaperIndex
    }),
    currentExam() {
      console.log('currentPaperIndex', this.currentPaperIndex)
      console.log('currentExam 1', this.paperList[this.currentPaperIndex])
      return this.paperList[this.currentPaperIndex] || {}
    },
    paperTotal() {
      return get(this.paperList, 'length', 0)
    },
    percent() {
      return Math.floor((this.doneNum * 100) / this.paperTotal)
    },
    doneNum() {
      return this.paperTotal - this.noDoneNum
    },
    noDoneNum() {
      return this.examDetailList.filter((item) => !item.selectOptionIds.length).length
    },
    // 是否为最后一题
    isLastTopic() {
      return this.currentPaperIndex + 1 >= this.paperTotal
    }
  },

  watch: {},

  onLoad({ id }) {
    this.clearStore()
    if (id) {
      this.typeId = id
      this.getExamList()
    }

    // 判断是否是查看训练结果

    // this.isViewTrainRecord = viewRecord == undefined ? true : false;
    // if (index != undefined) {
    //   this.setCurrentPaperIndex(Number(index));
    // }
  },
  mounted() {
    this.getRoute()
  },

  methods: {
    ...mapActions(['submitPapel']),
    ...mapMutations(['setExamDetailListItem', 'setExamDetailList', 'setCurrentPaperIndex', 'clearStore']),

    getRoute() {
      let pages = getCurrentPages()
      let curPage = pages[pages.length - 1]
      return curPage.options || curPage.$route.query
    },
    getValue(is) {
      console.log('getValue', is)
      this.isViewTrainRecord = is
      this.showQuestionAnalysis()
    },

    async getExamList() {
      let res = await getExamListByType(this.typeId)
      this.paperList = res.data

      for (let i of this.paperList) {
        i.selectOptionIds = []
        let correctIds = []
        for (let p of i.optionList) {
          if (p.rightFlag === '1') {
            correctIds.push(p.id)
          }
        }
        i.correctOptionIds = correctIds
      }
      this.setExamDetailList(
        this.paperList.map((item) => ({
          selectOptionIds: [],
          correctOptionIds: item.correctOptionIds,
          id: item.id,
          optionList: item.optionList,
          type: item.type,
          analysis: item.analysis
        }))
      )
      console.log(this.paperList)
    },
    handlePreview() {
      if (this.currentPaperIndex > 0) {
        this.setCurrentPaperIndex(this.currentPaperIndex - 1)
      }
      this.showQuestionAnalysis()
    },
    handleNext() {
      if (this.currentPaperIndex + 1 < this.paperTotal) {
        this.setCurrentPaperIndex(this.currentPaperIndex + 1)
      } else {
        this.tipDialogVisible = true
      }

      this.showQuestionAnalysis()
    },

    isSelect({ id }) {
      const selectOptionIds = get(this.examDetailList, `${this.currentPaperIndex}.selectOptionIds`, [])
      return selectOptionIds.includes(id)
    },
    handleSelect({ id }) {
      let selectOptionIds = get(this.examDetailList, `${this.currentPaperIndex}.selectOptionIds`, [])

      if (this.currentExam.type === '2') {
        if (includes(selectOptionIds, id)) {
          if (selectOptionIds.length <= 1) return
          selectOptionIds = selectOptionIds.filter((id) => id !== id)
        } else {
          selectOptionIds.push(id)
        }
      } else {
        selectOptionIds = [id]
      }
      console.log('currentExam 2', this.currentExam)
      this.setExamDetailListItem({
        correctOptionIds: this.currentExam.correctOptionIds,
        id: this.currentExam.id,
        selectOptionIds: selectOptionIds,
        optionList: this.currentExam.optionList,
        type: this.currentExam.type,
        analysis: this.currentExam.analysis
      })

      if (this.currentExam.type !== '2') {
        this.showQuestionAnalysis()
      }
    },

    multiTitleConfirm() {
      this.showAnalysis = true
      this.getCorrectAnswer()
      this.getYourAnswer()
    },

    handlePopup() {
      uni.navigateTo({
        url: `/pages/work/online-examination/training-answer-sheet?id=${this.typeId}`
      })
    },

    async handleSubmit() {
      uni.navigateTo({
        url: `/pages/work/online-examination/training-result?id=${this.typeId}`
      })
    },
    handleEnded() {
      uni.navigateBack({
        delta: 2
      })
    },

    // 显示试题解析
    showQuestionAnalysis() {
      console.log('currentPaperIndex', this.currentPaperIndex)
      console.log('examDetailList', this.examDetailList)
      // 当前题目是否作答
      let selectOptionIds = this.examDetailList[this.currentPaperIndex].selectOptionIds
      if (selectOptionIds.length > 0) {
        this.showAnalysis = true
        this.getYourAnswer()
        this.getCorrectAnswer()
      } else {
        this.showAnalysis = false
      }
    },

    getYourAnswer() {
      let choseIds = this.examDetailList[this.currentPaperIndex].selectOptionIds
      let { optionList } = this.currentExam
      let answerArr = []
      console.log(choseIds)
      console.log(optionList)
      if (this.currentExam.type !== '3') {
        answerArr = choseIds.map((id) =>
          get(
            this.currentExam.optionList.find((item) => item.id === id),
            'options'
          )
        )
      } else {
        answerArr = choseIds.map((id) =>
          get(
            this.currentExam.optionList.find((item) => item.id === id),
            'content'
          )
        )
      }
      // 对答案进行排序
      answerArr.sort()
      this.yourAnswer = answerArr.join()
    },

    getCorrectAnswer() {
      let choseIds = this.examDetailList[this.currentPaperIndex].correctOptionIds
      let { analysis, optionList } = this.currentExam
      let answerArr = []
      console.log(choseIds)
      console.log(optionList)
      if (this.currentExam.type !== '3') {
        answerArr = choseIds.map((id) =>
          get(
            this.currentExam.optionList.find((item) => item.id === id),
            'options'
          )
        )
      } else {
        answerArr = choseIds.map((id) =>
          get(
            this.currentExam.optionList.find((item) => item.id === id),
            'content'
          )
        )
      }
      // 对答案进行排序
      answerArr.sort()
      this.correctAnswer = answerArr.join()
      this.questionAnalysis = analysis
    }
  }
}
</script>

<style>
page {
  height: 100%;
}
</style>
<style scoped lang="scss" type="text/scss">
.container {
  background-color: #88b4c4;
  position: relative;
  height: 100%;
  overflow-y: auto;
  padding-bottom: 180rpx;
}
.page-banner {
  padding: 0 30rpx;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    font-size: 12px;
    color: #ffffff;

    .right {
      .time {
        transform: translateY(10%);
        width: 26rpx;
        height: 26rpx;
      }
      > text {
        padding-left: 10rpx;
      }
      .text {
        color: #dfe8eb;
      }
    }
    .num {
      padding-left: 20rpx;
      .big {
        font-size: 56rpx;
      }
    }
  }
  .progress {
    margin-top: 16rpx;
  }
  .grid-body {
    margin: 60rpx 0 0;
    padding: 30rpx;
    color: #333333;

    .type {
      width: 100rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #88b4c4;
      border-radius: 10rpx 10rpx 10rpx 10rpx;
      color: #fff;
      font-size: 12px;
      text-align: center;
    }

    .content {
      margin-top: 30rpx;
      margin-bottom: 40rpx;
      font-size: 30rpx;
      font-weight: bold;
      word-break: break-all;
    }

    .option {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx 30rpx 30rpx 20rpx;
      width: 100%;
      // min-height: 88rpx;

      background: #f5f5f5;
      border-radius: 10rpx 10rpx 10rpx 10rpx;
      margin-bottom: 20rpx;
      font-size: 30rpx;

      & text {
        display: inline-block;
        min-height: 48rpx;
        line-height: 48rpx;
        word-break: break-all;
      }
      &.active {
        background: #ebf2f5;
      }
      image {
        width: 48rpx;
        height: 48rpx;
        flex-shrink: 0;
      }
    }
    .btn-group {
      margin-top: 40rpx;
    }
    .analysis-box {
      margin-top: 40rpx;
      .answer {
        min-height: 50rpx;
        line-height: 50rpx;
        word-break: break-all;
        text {
          margin-right: 20rpx;
        }
      }
      .analysis {
        word-break: break-all;
        .big {
          font-size: 32rpx;
          color: #333333;
          font-weight: bold;
        }
      }
    }
    .preview {
      width: 300rpx;
      background-color: #fff;
      color: #88b4c4;
      border: 1px solid #88b4c4;
    }
    .next {
      width: 300rpx;
      color: #fff;
      background-color: #88b4c4;
    }
  }
}
.page-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 158rpx;
  background-color: #fff;
  padding-right: 30rpx;
  padding-left: 46rpx;

  .answer-sheet image {
    display: block;
    margin: 0 auto 5rpx;
    width: 54rpx;
    height: 54rpx;
  }
  .pause {
    width: 231rpx;
    color: #fff;
    background: #c4c088;
  }
  .submit {
    margin-left: 30rpx;
    width: 231rpx;
    color: #fff;
    background: #454a5e;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;

  .big-btn {
    border-radius: 44rpx 44rpx 44rpx 44rpx;
    font-size: 34rpx;
    text-align: center;
    height: 88rpx;
    line-height: 88rpx;
  }
  .small-btn {
    border-radius: 44rpx 44rpx 44rpx 44rpx;
    font-size: 24rpx;
    text-align: center;
    height: 66rpx;
    line-height: 66rpx;
    cursor: pointer;
  }
}
.confirm-btn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .small-preview {
    width: 200rpx;
    background-color: #fff;
    color: #88b4c4;
    border: 1px solid #88b4c4;
  }
  .small-next {
    width: 200rpx;
    color: #fff;
    background-color: #88b4c4;
  }
}
.pre-nex {
  width: 100%;
  display: flex;
  justify-content: space-between;
  cursor: pointer;
}
.disable {
  background-color: #dfdfdf !important;
  border: none !important;
  color: #fff !important;
  cursor: not-allowed;
  pointer-events: none;
}
</style>